package org.blackcat.common;

import java.io.*;

/**
 * Created by Duo Duo on 2017/1/5.
 */
public class SerializeUtils {

    /**
     * 序列化
     * @param obj 输入对象
     * @return
     */
    public static byte[] serialize(Object obj){
        try {
            try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream os = new ObjectOutputStream(bos);){
                os.writeObject(obj);
                byte[] bytes = bos.toByteArray();
                return bytes;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 反序列化
     * @param bytes
     * @return
     */
    public static Object unSerialize(byte[] bytes){
        try {
            try(ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bis)){
                return ois.readObject();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
